<?php
class Sqlite3Adapter extends SqliteAdapter
{
    protected static $openedConnections = array();
    protected $statement;

    public function Sqlite3Adapter($name)
    {
        parent::__construct($name);
        $path = DIR_CONFIG.DS.$this->name;
        $this->driver = new PDO("sqlite:$path");
        self::Add($this->name, $this);
    }

    public static function Get($name)
    {
        if (!self::IsExisted($name))
            new Sqlite3Adapter($name);
        return self::$openedConnections[$name];
    }

    protected static function Add($name, $conn)
    {
        self::$openedConnections[$name] = $conn;
    }

    protected static function Remove($name)
    {
        unset(self::$openedConnections[$name]);
    }

    protected static function IsExisted($name)
    {
        return isset(self::$openedConnections[$name]);
    }

    public static function CloseAll()
    {
        foreach (self::$openedConnections as $conn)
        {
            $conn->Close();
        }
    }

    public function GetInsertId()
    {
        return $this->driver->lastInsertId();
    }

    public function GetAffectedRows()
    {
        return $this->statement->rowCount();
    }

    protected function FetchResult($result)
    {
        return $result->fetchAll();
    }

    public function ExecuteMulti($sql)
    {
        return $this->driver->exec($sql);
    }

    public function EscapeString($string)
    {
        return String::EscapeString($string);
    }

    public function GetLastError()
    {
        return $this->driver->errorCode();
    }

    public function GetErrorMessage()
    {
        $err = $this->driver->errorInfo();
        return isset($err[2]) ? $err[2] : null;
    }

    public function Execute($sql)
    {
        if (get_class($sql) == 'SqlQuery') $sql = $this->ToSql($sql);

        try
        {
            if (AppConfig::GetInstance()->IsDebugMode())
            {
                $timer = new Timer();
                $this->statement = $this->driver->query($sql);
                Log::LogSql($sql, $this->GetAffectedRows(), $timer->Stop());
            }
            else
                $this->statement = $this->driver->query();
        }
        catch (Exception $ex)
        {
            $errno = $this->GetLastError();
            Log::LogSqlError($this->GetErrorMessage(), $sql, $errno);
        }

        return $this->statement;
    }
}
?>
